import React from "react";
import { Icon, Input, Form, Select, Radio, Checkbox, DatePicker, Switch } from "antd";
import Selector from "components/selector";
import Chooser from "components/chooser";
import Searcher from "components/searcher";
import Inputter from "components/inputter";
import DateRangePicker from "components/date-range-picker";
import "styles/components/advanced-search/advanced-search-form-item.scss";
import { deepCopy } from "share/common";
import MultiSelector from "components/multi-selector"
import MultiSelectorV2 from "components/template/multi-selector"
import AllSelector from "components/template/all-selector/all-selector";


const { MonthPicker, WeekPicker, RangePicker } = DatePicker;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;


function AdvancedSearchFormItem({ form, field }) {
  /**
   * 内部支持的组件map
   * 如果后续产生了更多的内部组件，可以在这里添加
   * 除了以下的组件，如果其他注入的组件想通过onSearch传出，那么需要自己封装成antd的Form型组件注入
   */
  let componentsMap = {
    Input,
    Select,
    Selector,
    Chooser,
    Searcher,
    Inputter,
    DatePicker,
    MonthPicker,
    WeekPicker,
    RangePicker,
    DateRangePicker,
    RadioGroup,
    CheckboxGroup,
    Switch,
    MultiSelector,
    AllSelector,
    MultiSelectorV2
  };

  let getComponentProps = ({ component, props }) => {
    if (component === "Selector") {
      //因为原始Selector中只返回对应key值，这里需要渲染筛选标签，所以这里强制给所有selector增加entity参数
      return Object.assign({}, props, { entity: true });
    } else if (["Chooser", "Searcher"].indexOf(component) > -1) {
      //因为onlyNeed模式下只返回对应key值，所以这里强制清除onlyNeed参数
      return Object.assign({}, props, { onlyNeed: false });
    } else {
      return Object.assign({}, props);
    }
  };

  let getFieldLabel = ({ label, icon }) => {
    return icon ? (
      <span>
        <Icon type={icon} className="pin-icon" />
        {label}
      </span>
    ) : (
      label
    );
  };

  const { getFieldDecorator } = form;
  const { id, extra, component = <Input />, initialValue, decorator } = field;

  const element =
    typeof component === "string" ? (
      componentsMap[component] ? (
        React.createElement(
          componentsMap[component],
          getComponentProps(field),
          field.children || null
        )
      ) : (
        <Input />
      )
    ) : (
      component
    );

  return (
    <FormItem
      className="advanced-search-form-item"
      label={getFieldLabel(field)}
      colon={false}
      key={id}
    >
      {extra ? (
        typeof component === "string" ? (
          <Input></Input>
        ) : (
          component
        )
      ) : (
        getFieldDecorator(id, {
          initialValue: initialValue ? deepCopy(initialValue) : undefined,
          ...decorator,
        })(element)
      )}
    </FormItem>
  );
}

export default AdvancedSearchFormItem;
